import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
import os

def send_mail(latest_report):
    smtpserver = 'smpt.qq.com'
    user = '310161033@qq.com'
    password = 'ddddddd'

    sender = '310161033@qq.com'
    receviers = ['310161033@qq.com']

    subject = 'python自动化测试报告'

    #构建附件内容
    send_file = open(latest_report,'rb').read()
    filename = os.path.basename(latest_report)
    enclosure = MIMEText(send_file,'base64','utf-8')
    enclosure['Content-type'] = 'application/octet-stream'
    enclosure['Content-Disposition'] = 'attachment;filename='+filename

    #内容
    f = open(latest_report,'rb')
    mail_content = f.read()
    f.close()

    #构建发送与接收者信息
    msg = MIMEMultipart()
    msg.attach(MIMEText(mail_content,'html','utf-8'))
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = sender
    msg['To'] = ','.join(receviers)
    msg.attach(enclosure)

    smtp = smtplib.SMTP_SSL(smtpserver, 465)
    smtp.helo(smtpserver)
    smtp.ehlo(smtpserver)
    smtp.login(user,password)

    print("Send Mail Start...")
    smtp.sendmail(sender,receviers,msg.as_string())
    smtp.quit()
    print("Send Mail end...")

def lateset_report(report_dir):
    lists = os.listdir(report_dir)
    print(lists)
    lists.sort(key=lambda fn:os.path.getatime(report_dir + '\\' + fn))
    print("the latest test_report is " + lists[-1])
    file = report_dir + '/' + lists[-1]
    print(file)
    return file

